<script setup lang="ts">

import Chat from "./Chat.vue";
import {getCurrentInstance, nextTick, Ref, ref, watch} from "vue";
import {ChatItem, ChatMessageData, Dictionary, GroupUser} from "common";
import socket from "../socket/socket.ts";
import {MessageType, TextMessage} from "message";
import {useRootStore} from "../stores/root.ts";
import {storeToRefs} from "pinia";
import {getGroupUsers, loadChatHistory, loadGroupChatHistory, setCookie} from "../api";
import EmojiPanel from "./EmojiPanel.vue";
import { invoke } from '@tauri-apps/api/tauri';

const messages = ref<ChatMessageData[]>([])
const message = ref('')
const chat = ref<InstanceType<typeof Chat> | null>(null)
const rootStore = useRootStore()
const {userInfo,Cookie}=storeToRefs(rootStore)
const target:Ref<Dictionary> = ref({})
const groupUsers:Ref<GroupUser[]> = ref([])
const showName = ref(false)
const currentChatItem = ref<ChatItem|null>(null)

watch(userInfo,()=>{
  console.log(userInfo.value)
},{deep:true})

let tooltipTimout : number | null = null
const showEmptyTextToolTip = ref(false)
const pageIndex = ref(0);
const pageSize = ref(10);
const ctx = getCurrentInstance() as any
const showNotEmpty = ()=>{
  if(tooltipTimout){
    clearTimeout(tooltipTimout)
  }
  showEmptyTextToolTip.value=true
  tooltipTimout = setTimeout(()=>{
    showEmptyTextToolTip.value=false
  },2000)
}

const sendMessage = (event: MouseEvent)=>{
  if(event){
    event.preventDefault()
  }
  if(!message.value){
    showNotEmpty()
    return
  }
  messages.value.push({
    avatar: userInfo.value!.avatar,
    message:message.value,
    sendByMe:true,
    senderId:userInfo.value!.userId,
    name:userInfo.value!.name,
  })

  let data:TextMessage = {
    type:MessageType.TEXT,
    userId:userInfo.value!.userId,
    receiverId:target.value.userId,
    content:message.value,
    group:showName.value
  }
  message.value=''
  socket.sendMessage(data)

  nextTick(()=>{
    chat.value?.scrollToEnd()
  })

}

const loadHistory = async ()=>{
  setCookie(Cookie.value)
  let chatItem:ChatItem = currentChatItem.value!;
  let list = []
  if(chatItem.targetType===0){
    list = (await loadChatHistory(chatItem.friendId,pageIndex.value,pageSize.value)).data.data
  }else{
    list = (await loadGroupChatHistory(chatItem.friendId,pageIndex.value,pageSize.value)).data.data
  }
  messages.value = list.map(item=>{
    console.log(item)
    let sendByMe = item.senderId===userInfo.value?.userId;
    return{
      avatar:sendByMe?userInfo.value?.avatar:userMap.value[item.senderId].avatar,
      sendByMe:sendByMe,
      message:item.message,
      senderId:item.senderId,
      name:userMap.value[item.senderId].name
    }
  })
}

const userMap:Ref<Dictionary>=ref({})

const openChat = async (chatItem:ChatItem)=>{
  currentChatItem.value=chatItem;
  target.value.userId=chatItem.friendId
  target.value.type=chatItem.targetType
  target.value.avatar = chatItem.avatar

  if(chatItem.targetType===0){
    showName.value=false
    userMap.value[chatItem.friendId]= {userId:chatItem.friendId,avatar:chatItem.avatar,name:chatItem.name};
    userMap.value[userInfo.value!.userId]=userInfo
    console.log(userMap)
  }else{
    showName.value=true
    groupUsers.value = (await getGroupUsers(chatItem.friendId)).data.data
    groupUsers.value.forEach(item=>{
      userMap.value[item.userId]=item
    })
  }
  await loadHistory()
  await nextTick(()=>{
    chat.value?.scrollToEnd()
  })


}

const handleMessage = (message:any)=>{

  if(message.group){
    if(!message.receiverId===target.value.userId)return;
  }else{
    if(message.userId!==target.value.userId)return;
  }
  if(message.userId===userInfo.value?.userId)return;
  messages.value.push({
    avatar:userMap.value[message.userId].avatar,
    message:message.content,
    senderId:message.userId,
    name:userMap.value[message.userId].name
  })
  nextTick(()=>{
    chat.value?.scrollToEnd()
  })
}
const onScroll = async (event:UIEvent)=>{
  console.log((event.target as Element).scrollTop)
  if((event.target as Element).scrollTop===0){
    pageSize.value=pageSize.value+10
    let scrollHeight = (event.target as Element).scrollHeight;
    await loadHistory()
    await nextTick(()=>{
      (event.target as Element).scrollTop = (event.target as Element).scrollHeight - scrollHeight
    })

  }
}

const uploadImage = async ()=>{
  const fileType = ['jpg','png','bmp']
  const inputFile = document.createElement("input")
  inputFile.type = "file"
  inputFile.style.display = "none"
  document.body.appendChild(inputFile)
  inputFile.click()
  inputFile.addEventListener("change",function() {
    const file = inputFile.files![0];
    var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
    if (!fileType.includes(testmsg)) {
      document.body.removeChild(inputFile);
      return false;
    }
    const formData = new FormData();
    formData.append("file", file);

  })
}

const startVoiceCall = async () => {
  if (!currentChatItem.value) return;
  
  try {

    await invoke('open_video_chat_window', {
      user: {
        userId: currentChatItem.value.friendId.toString(),
        name: currentChatItem.value.name,
        avatar: currentChatItem.value.avatar||""
      },
      isIncoming: false
    });
  } catch (error) {
    console.error('启动语音通话失败:', error);
  }
}

const startVideoCall = async () => {
  console.log('点击视频聊天按钮');
  console.log('currentChatItem:', currentChatItem.value);
  
  if (!currentChatItem.value) {
    console.log('没有选择聊天对象，无法启动视频通话');
    return;
  }
  
  try {
    console.log("startVoiceCall",currentChatItem.value);
    console.log('正在调用 open_video_chat_window...');
    await invoke('open_video_chat_window', {
      user: {
        userId: currentChatItem.value.friendId.toString(),
        name: currentChatItem.value.name,
        avatar: currentChatItem.value.avatar||"",
      },
      isIncoming: false
    });
    console.log('视频聊天窗口调用成功');
  } catch (error) {
    console.error('启动视频通话失败:', error);
  }
}

defineExpose({handleMessage,openChat})
</script>

<template>
<div class="chat-container">
  <Chat :messages="messages" ref="chat" :showName="showName" :onscroll="onScroll"></Chat>
  <div class="input-container">
    <div class="tool-bar">
      <EmojiPanel @emoji="(emoji:string)=>{message+=emoji}">
      </EmojiPanel>
      <v-menu>
        <template v-slot:activator="{props}">
          <v-icon  icon="mdi-video" v-bind="props"></v-icon>
        </template>
        <v-list>
          <v-list-item value="1" @click="startVoiceCall">语音聊天</v-list-item>
          <v-list-item value="2" @click="startVideoCall">视频聊天</v-list-item>
        </v-list>
      </v-menu>
      <v-icon icon="mdi-image" @click="uploadImage" ></v-icon>

    </div>
    <div class="text-area">
      <v-textarea @keydown.enter="sendMessage($event)" v-model="message" variant="plain" no-resize density="compact" hide-details>

      </v-textarea>
    </div>
    <div class="footer-container">
      <v-fade-transition>
        <div class="tips" v-show="showEmptyTextToolTip">不能发送空白信息</div>
      </v-fade-transition>
      <v-btn color="green"  @click="sendMessage">发送</v-btn>
    </div>
  </div>
</div>
</template>

<style scoped lang="scss">
.chat-container{
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding-right: 2px;
  .input-container{
    background: #eee;
    .tool-bar{
      border-top: solid 1px #ddd;
      padding: 5px 20px;
      display: flex;
      align-items: center;
      gap: 10px;

      .v-icon{
        cursor: pointer;
        transition: background-color .2s;
        &:hover{
          background-color: rgba(0,0,0,0.1);
        }
        
      }
    }
    .text-area{
      padding: 0 20px;
    }
    .footer-container{
      padding: 10px 20px;
      text-align: right;
      position: relative;
      .tips{
        position: absolute;
        bottom: 100%;
        right: 20px;
        background: rgba(44,44,44,0.7);
        color: white;
        padding: 5px 10px;
        border-radius: 3px;
      }
    }
  }

}
</style>
